package com.security.door.controller.fileUpload;

import com.security.door.core.wrapper.WrapMapper;
import com.security.door.core.wrapper.Wrapper;
import com.security.door.model.vo.fileParamVo;
import com.security.door.model.vo.uploadResultVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;

@RestController
@Api(value = "WEB - fileUploadController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class fileUploadController {

    @Autowired
    HttpSession session;
    @Autowired
    HttpServletRequest httpServletRequest;

    @PostMapping("/file/upLoad")
    private Wrapper upLoadFile(@RequestParam("file") MultipartFile file) throws Exception {
        //返回数据
        uploadResultVo uploadresult = new uploadResultVo();
        ////////resource文件路径
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        ////////上传文件路径
        File upload = new File(path.getAbsolutePath(), "static/uploadfile/");
        String rootUrl = upload.getAbsolutePath();
        if (!upload.exists()) upload.mkdirs();

        String origName = file.getOriginalFilename();// 文件原名称
        if (file != null) {
            //存放图片文件的路径
            File uploadedFile = new File(rootUrl + "//" + origName);
            OutputStream os = new FileOutputStream(uploadedFile);
            InputStream is = file.getInputStream();
            byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度
            int length = 0;
            int i = 0;
            while ((length = is.read(buf)) > 0) {
                i++;
                os.write(buf, 0, length);
            }
            //关闭流
            os.flush();
            is.close();
            os.close();
            uploadresult.setUrl(rootUrl);
            uploadresult.setName(origName);
        }
        return WrapMapper.ok(uploadresult);
    }
}
